//
//  OAuthViewController.swift
//  Weibo8023
//
//  Created by styshy on 15/12/7.
//  Copyright © 2015年 sz. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    private lazy var webView = UIWebView()
    
    // MARK:- 监听方法
    @objc private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFill(){
        let js = "document.getElementById('userId').value = '13817049701';" +
        "document.getElementById('passwd').value = 'ABClove.8023';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
        
        title = "登陆新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登陆", style: .Plain, target: self, action: "autoFill")
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 加载页面
        self.webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
    }

}


// MARK:-UIWebViewDelegate
extension OAuthViewController{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 1.判断主机的host是不是百度，不是就返回true
        guard let url = request.URL where url.host == "www.baidu.com" else{
            return true
        }
        
        // 2.从百度的url中判断是否存在code =
        guard let query = url.query where query.hasPrefix("code=") else{
            print("取消授权")
            return false
        }
        
        // 3.从query中获取授权码
        let code = query.substringFromIndex("code=".endIndex)
        print("授权码是 " + code)
        
        // 4. 加载 accessToken
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccessed) -> () in
            
            if !isSuccessed {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                delay(0.5){
                    self.close()
                }
                return
            }
            
            print("成功了")
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                SVProgressHUD.dismiss()
                // 通知中心是同步的，一旦发送通知，会先执行监听方法，直接结束后，才执行后续代码
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "welcome")
            })
        }

        return false
        
    }
}
